package com.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.srb.core.mapper.DictMapper;
import com.srb.core.pojo.dto.ExcelDictDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建监听器
 */
@Slf4j
@Component
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private List<ExcelDictDTO> list = new ArrayList<>();
    //模拟每5条存储一次数据
    static final int BATCH_COUNT = 5;

    @Autowired
    private DictMapper dictMapper;

    /**
     * 每一条数据解析都会来调用
     * @param excelDictDTO
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析一条数据：{}",excelDictDTO);
        list.add(excelDictDTO);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        log.info("{} 条数据存储到数据库...",list.size());
        dictMapper.insertBatch(list);
        log.info("{} 条数据存储到数据库成功!",list.size());
    }

    /**
     * 所有数据解析完了都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当数据记录数量不足BATCH_COUNT条,最终一次性存储剩余的数据
        saveData();
        log.info("所有数据都解析完成!");
    }
}
